package com.heisenhub.uua.service;

import com.heisenhub.common.oauth.entity.UuaUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import java.util.Map;

@Slf4j
public abstract class AbstractCustomTokenGranter extends AbstractTokenGranter {

    private final OAuth2RequestFactory requestFactory;

    protected AbstractCustomTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.requestFactory = requestFactory;
    }


    /**
     *  其他方式登入
     * @param client
     * @param tokenRequest
     * @return
     */
    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        log.info("【方式登入:{}】 ClientId:{}" ,tokenRequest.getGrantType() ,tokenRequest.getClientId());
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        UserDetails userDetails = userLogin(parameters);


        OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest);

        //PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails, parameters, userDetails.getAuthorities());
        authentication.setDetails(userDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(storedOAuth2Request, authentication);
        return oAuth2Authentication;
    }

    /**
     * 登入
     *
     * @param parameters
     * @return
     */
    protected abstract UserDetails userLogin(Map<String, String> parameters);
}
